<template>
  <div class="admin-attendance-view">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.schoolRecords') }}</span>
      </div>
      
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item :label="$t('course.title')">
          <el-select v-model="queryForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" clearable>
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('group.title')">
          <el-select v-model="queryForm.groupId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('group.title')" clearable>
            <el-option
              v-for="group in groupList"
              :key="group.id"
              :label="group.name"
              :value="group.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('attendance.status')">
          <el-select v-model="queryForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')" clearable>
            <el-option :label="$t('attendance.normal')" :value="0"></el-option>
            <el-option :label="$t('attendance.late')" :value="1"></el-option>
            <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
            <el-option :label="$t('attendance.absent')" :value="3"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('attendance.dateRange')">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            :range-separator="$t('common.to')"
            :start-placeholder="$t('attendance.startDate')"
            :end-placeholder="$t('attendance.endDate')"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">{{ $t('common.search') }}</el-button>
          <el-button @click="resetQuery">{{ $t('common.reset') }}</el-button>
          <el-button type="success" @click="exportAttendance" class="export-button" :disabled="exporting">
            <i class="el-icon-download"></i> <span class="button-text">{{ $t('attendance.exportRecords') }}</span>
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="attendanceList" style="width: 100%">
        <el-table-column :label="$t('attendance.studentInfo')">
          <template slot-scope="scope">
            {{ getStudentName(scope.row.userId) }}
            <el-tag size="mini">{{ getStudentId(scope.row.userId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('group.title')">
          <template slot-scope="scope">
            {{ getStudentGroup(scope.row.userId) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('course.title')">
          <template slot-scope="scope">
            {{ getCourseName(scope.row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkInTime" :label="$t('attendance.checkTime')"></el-table-column>
        <el-table-column :label="$t('attendance.status')">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" :label="$t('common.remark')"></el-table-column>
        <!-- PC端操作列 -->
        <el-table-column :label="$t('common.operation')" width="150" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewDetail(scope.row)">{{ $t('common.view') + $t('common.detail') }}</el-button>
          </template>
        </el-table-column>
        
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="160"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button 
                  type="text" 
                  size="mini" 
                  @click="viewDetail(scope.row)">
                  <i class="el-icon-view"></i> {{ $t('common.view') + $t('common.detail') }}
                </el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 考勤详情对话框 -->
    <el-dialog :title="$t('attendance.recordDetail')" :visible.sync="detailDialogVisible" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item :label="$t('attendance.studentName')">{{ currentRecord.studentName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('user.id')">{{ currentRecord.studentId }}</el-descriptions-item>
        <el-descriptions-item :label="$t('group.title')">{{ currentRecord.groupName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.courseName')">{{ currentRecord.courseName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.checkTime')">{{ currentRecord.checkInTime }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.status')">{{ getStatusText(currentRecord.status) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('attendance.checkLocation')">
          {{ $t('attendance.longitude') }}: {{ currentRecord.locationLongitude }}, {{ $t('attendance.latitude') }}: {{ currentRecord.locationLatitude }}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('common.remark')">{{ currentRecord.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { exportFile } from '@/utils/exportHelper'

export default {
  name: 'AdminAttendanceView',
  data() {
    return {
      queryForm: {
        courseId: null,
        groupId: null,
        status: null,
        startDate: null,
        endDate: null,
        current: 1,
        size: 10
      },
      dateRange: [],
      courseList: [],
      groupList: [],
      attendanceList: [],
      total: 0,
      detailDialogVisible: false,
      currentRecord: {},
      studentMap: new Map(),
      courseMap: new Map(),
      groupMap: new Map(),
      isMobile: false,
      exporting: false
    }
  },
  watch: {
    dateRange(val) {
      if (val) {
        this.queryForm.startDate = val[0]
        this.queryForm.endDate = val[1]
      } else {
        this.queryForm.startDate = null
        this.queryForm.endDate = null
      }
    }
  },
  created() {
    this.getCourseList()
    this.getGroupList()
    this.getAttendanceList()
    this.checkScreenSize()
  },
  mounted() {
    window.addEventListener('resize', this.checkScreenSize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkScreenSize)
  },
  methods: {
    // 检查屏幕尺寸并设置相应的布局
    checkScreenSize() {
      this.isMobile = document.body.clientWidth < 768
    },
    async getCourseList() {
      try {
        const res = await request.get('/course/page', {
          params: { current: 1, size: 1000 }
        })
        this.courseList = res.data.records
        this.courseMap = new Map(this.courseList.map(course => [course.id, course.name]))
      } catch (error) {
        this.$message.error('获取课程列表失败')
      }
    },
    async getGroupList() {
      try {
        const res = await request.get('/group/list')
        this.groupList = res.data
        this.groupMap = new Map(this.groupList.map(group => [group.id, group.name]))
      } catch (error) {
        this.$message.error('获取班级列表失败')
      }
    },
    async getAttendanceList() {
      try {
        const res = await request.get('/attendance/page', {
          params: this.queryForm
        })
        this.attendanceList = res.data.records
        this.total = res.data.total
        
        // 获取学生信息
        const studentIds = [...new Set(this.attendanceList.map(record => record.userId))]
        await this.getStudentsInfo(studentIds)
      } catch (error) {
        this.$message.error('获取考勤记录失败')
      }
    },
    async getStudentsInfo(studentIds) {
      try {
        for (const id of studentIds) {
          if (!this.studentMap.has(id)) {
            const res = await request.get(`/user/${id}`)
            this.studentMap.set(id, res.data)
          }
        }
      } catch (error) {
        console.error('获取学生信息失败:', error)
      }
    },
    getStudentName(userId) {
      const student = this.studentMap.get(userId)
      return student ? student.name : userId
    },
    getStudentId(userId) {
      const student = this.studentMap.get(userId)
      return student ? student.id : userId
    },
    getStudentGroup(userId) {
      const student = this.studentMap.get(userId)
      if (student && student.groupId) {
        return this.getGroupName(student.groupId)
      }
      return this.$t('group.unassigned')
    },
    getCourseName(courseId) {
      return this.courseMap.get(courseId) || courseId
    },
    getGroupName(groupId) {
      return this.groupMap.get(groupId) || groupId
    },
    getStatusText(status) {
      const statusMap = {
        0: this.$t('attendance.normal'),
        1: this.$t('attendance.late'),
        2: this.$t('attendance.earlyLeave'),
        3: this.$t('attendance.absent')
      }
      return statusMap[status] || this.$t('common.unknown')
    },
    getStatusType(status) {
      const typeMap = {
        0: 'success',
        1: 'warning',
        2: 'warning',
        3: 'danger'
      }
      return typeMap[status] || 'info'
    },
    handleQuery() {
      this.queryForm.current = 1
      this.getAttendanceList()
    },
    resetQuery() {
      this.queryForm = {
        courseId: null,
        groupId: null,
        status: null,
        startDate: null,
        endDate: null,
        current: 1,
        size: 10
      }
      this.dateRange = []
      this.getAttendanceList()
    },
    handleSizeChange(val) {
      this.queryForm.size = val
      this.getAttendanceList()
    },
    handleCurrentChange(val) {
      this.queryForm.current = val
      this.getAttendanceList()
    },
    viewDetail(row) {
      this.currentRecord = {
        ...row,
        studentName: this.getStudentName(row.userId),
        studentId: this.getStudentId(row.userId),
        groupName: this.getStudentGroup(row.userId),
        courseName: this.getCourseName(row.courseId)
      }
      this.detailDialogVisible = true
    },
    exportAttendance() {
      // 构建查询参数
      const params = {
        courseId: this.queryForm.courseId,
        groupId: this.queryForm.groupId,
        status: this.queryForm.status,
        startDate: this.queryForm.startDate,
        endDate: this.queryForm.endDate
      };
      
      // 清除空值
      Object.keys(params).forEach(key => {
        if (params[key] === undefined || params[key] === null || params[key] === '') {
          delete params[key];
        }
      });
      
      // 使用导出工具导出
      exportFile({
        url: '/attendance/export',
        params,
        defaultFileName: this.$t('attendance.records'),
        beforeExport: () => {
          this.exporting = true;
        },
        afterExport: () => {
          this.exporting = false;
        },
        fileType: 'csv',
        getCustomFileName: (params) => {
          // 生成自定义文件名
          const now = new Date();
          const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
          let fileName = `${this.$t('attendance.records')}_${dateStr}`;
          
          // 如果指定了日期，添加日期
          if (params.startDate || params.endDate) {
            fileName += `_${params.startDate ? params.startDate.split('T')[0] : ''}${this.$t('common.to')}${params.endDate ? params.endDate.split('T')[0] : ''}`;
          }
          
          // 如果指定了课程，添加课程名称
          if (params.courseId && this.courseList) {
            const course = this.courseList.find(c => c.id === params.courseId);
            if (course) {
              fileName += `_${course.name}`;
            }
          }
          
          // 如果指定了状态，添加状态名称
          if (params.status !== undefined) {
            fileName += `_${this.getStatusText(params.status)}`;
          }
          
          return fileName;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.admin-attendance-view {
  padding: 20px;
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }
  
  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
}

@media screen and (max-width: 768px) {
  .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .el-form-item .el-form-item__content {
    width: 100%;
  }
  
  .el-select, .el-date-editor {
    width: 100% !important;
  }
  
  .el-form-item:last-child {
    margin-top: 15px;
    display: flex;
    flex-direction: column;
    align-items: stretch;
  }
  
  .el-form-item:last-child .el-button {
    margin-top: 8px;
    margin-left: 0 !important;
    width: 100%;
  }
  
  .export-button {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .button-text {
    margin-left: 5px;
  }
}
</style> 